package com.example.healthmanagement.controller;

import com.example.healthmanagement.entity.*;
import com.example.healthmanagement.mapper.ChildinformationtableMapper;
import com.example.healthmanagement.pojo.Childinformationtable;
import com.example.healthmanagement.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.plaf.PanelUI;
import java.util.*;
import java.util.stream.Collectors;

// UserController.java
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 响应请求分页数据
     */
    protected static TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(User user,HttpServletRequest request)
    {
        Integer pageNum = Integer.valueOf(request.getParameter("pageNum"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        PageHelper.startPage(pageNum, pageSize);
        List<User> allUsers = userService.getAllUsers();
        return getDataTable(allUsers);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
String o = "{\"list\":[\n" +
        "    {\n" +
        "        \"name\": \"System\",\n" +
        "        \"path\": \"/system\",\n" +
        "        \"hidden\": false,\n" +
        "        \"redirect\": \"noRedirect\",\n" +
        "        \"component\": \"Layout\",\n" +
        "        \"alwaysShow\": true,\n" +
        "        \"meta\": {\n" +
        "            \"title\": \"系统管理\",\n" +
        "            \"icon\": \"system\",\n" +
        "            \"noCache\": false,\n" +
        "            \"link\": null\n" +
        "        },\n" +
        "        \"children\": [\n" +
        "            {\n" +
        "                \"name\": \"User\",\n" +
        "                \"path\": \"user\",\n" +
        "                \"hidden\": false,\n" +
        "                \"component\": \"system/user/index\",\n" +
        "                \"meta\": {\n" +
        "                    \"title\": \"用户管理\",\n" +
        "                    \"icon\": \"user\",\n" +
        "                    \"noCache\": false,\n" +
        "                    \"link\": null\n" +
        "                }}\n" +
        "]}]}";

        ObjectMapper objectMapper = new ObjectMapper();
        RouterList list = null;
        try {
            list = objectMapper.readValue(o, RouterList.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return AjaxResult.success(list.getList());
    }

    /**
     * 删除用户`
     */
    @PostMapping("delete")
    public AjaxResult remove(@RequestBody User user)
    {
        userService.deleteByUserID(user);
        return AjaxResult.success();
    }

    @GetMapping("getUser")
    public AjaxResult getAllUsers(LoginBo loginBo) {
        AjaxResult ajax = AjaxResult.success();
        User user = new User();
        UserVo userVo = new UserVo();
        if(loginBo.getUserId() != null){
            user = userService.getUserById(loginBo.getUserId());

                userVo.setUserID(user.getUserID());
                userVo.setUsername(user.getUsername());
                userVo.setPassword(user.getPassword());
                List<ChildInformation> childList = userService.getChildList(user.getUserID());
            List<ChildInformationVo> childInformationVos = new ArrayList<>();

            for (ChildInformation childInformation : childList) {
                List<Report> sport = userService.findSport(childInformation.getChildID());
                //List<ChildSportRecords> sportListByChildID = userService.getSportListByChildID(childInformation.getChildID());
                ChildInformationVo childInformationVo = new ChildInformationVo();
                childInformationVo.setReportList(sport);
                childInformationVo.setChildName(childInformation.getChildName());
                childInformationVo.setAge(childInformation.getAge());
                childInformationVos.add(childInformationVo);
            }
                userVo.setChildInformationVos(childInformationVos);
        }
        ajax.put("user", userVo);
        Set<String> roles = new HashSet<String>();
        roles.add("admin");
        ajax.put("roles", roles);
        Set<String> perms = new HashSet<String>();
        perms.add("*:*:*");
        ajax.put("permissions", perms);
        //ajax.put("posts", );
        ArrayList<Integer> postIds = new ArrayList<>();
        postIds.add(2);
        ajax.put("postIds", postIds);
        ajax.put("roleIds", postIds);
        ajax.put("data", userVo);
        return ajax;
    }

    @GetMapping("captchaImage")
    public AjaxResult captchaImage() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("captchaEnabled",false );
        return ajax;
    }

    /**
     * 注销
     * @return
     */
    @PostMapping("/logout")
    public String logout(HttpServletRequest httpRequest){
        //先修改用户状态 再跳转退出登录
        httpRequest.getSession().removeAttribute("token");
        return "http://localhost/login";
    }

    @PostMapping("/login")
    public Response<LoginInfo> login(@RequestBody LoginForm loginForm) {
        if (loginForm.getUsername().equals("admin")) {
            Response<LoginInfo> response = new Response<>(1, "登录成功");
            response.setData(new LoginInfo(UUID.randomUUID().toString(), "1"));
            return response;
        }

        if (userService.checkUser(loginForm)) {
            Response<LoginInfo> response = new Response<>(200, "登录成功");
            response.setData(new LoginInfo(UUID.randomUUID().toString(), "2", userService.getUserId(loginForm.getUsername())));

            return response;
        } else {

            return new Response<>(200, "失败");
        }

    }

    @PostMapping("/systemLogin")
    public AjaxResult login(@RequestBody LoginForm loginForm, HttpServletRequest httpRequest) {
        AjaxResult ajax = AjaxResult.success();
//        if (loginForm.getUsername().equals("admin")) {
//            Response<LoginInfo> response = new Response<>(1, "登录成功");
//            //response.setData(new LoginInfo(UUID.randomUUID().toString(), "1"));
//            httpRequest.getSession().setAttribute("token"+"admin", UUID.randomUUID().toString());
//            ajax.put("token", UUID.randomUUID().toString());
//            return ajax;
//        }

        if (userService.checkUser(loginForm)) {
            Response<LoginInfo> response = new Response<>(200, "登录成功");
            response.setData(new LoginInfo(UUID.randomUUID().toString(), "2", userService.getUserId(loginForm.getUsername())));
            httpRequest.getSession().setAttribute("token"+loginForm.getUsername(), UUID.randomUUID().toString());
            ajax.put("token",UUID.randomUUID().toString());
            return ajax;
        } else {
            return AjaxResult.error("用户名密码错误");
        }

    }

    @PostMapping("/register")
    public Response<String> register(@RequestBody User user) {
        Response<String> response = new Response<>(200, "注册成功");
        if (userService.createUser(user)) {
            response.setMsg("帐号已存在");
            return response;
        }
        return response;
    }

    @PostMapping("/changePassword")
    public Boolean changePassword(@RequestBody User user) {

        return false;
    }


    @PostMapping("/addUser")
    public AjaxResult addUser(@RequestBody User user) {
        boolean user1 = userService.createUser(user);
        if(user1){
            return AjaxResult.success();
        }
        return AjaxResult.error(0,"名称已存在");
    }

    @PostMapping("/updateUser")
    public AjaxResult updateUser(@RequestBody UserVo userVo) {
        User user = new User();
        user.setUserID(userVo.getUserID());
        user.setUsername(userVo.getUsername());
        user.setPassword(userVo.getUsername());
        boolean user1 = userService.updateUser(user);
        List<ChildInformationVo> childInformationVos = userVo.getChildInformationVos();
        for (ChildInformationVo childInformationVo : childInformationVos) {
            for (Report report : childInformationVo.getReportList()) {
                userService.updateReport(report);
            }
        }
        if(user1){
            return AjaxResult.success();
        }
        return AjaxResult.error(500,"用户不存在");
    }

    @PostMapping("/addChild")
    public Boolean addChild(@RequestBody AddChildInfo addChildInfo) {
        userService.addChild(addChildInfo.getUserID(), addChildInfo.getChildInformation());
        return true;
    }

    @GetMapping("/getFoodInfo")
    public List<FoodInfo> getFoodInfo() {
        return userService.getFoodInfo();
    }

    @GetMapping("/getSportInfo")
    public List<SportInfo> getSportInfo() {
        return userService.getSportInfo();
    }

    @PostMapping("/getChildList")
    public List<ChildInformation> getChildList(@RequestBody Integer userID) {
        return userService.getChildList(userID);
    }

    @PostMapping("/getChildById")
    public ChildInformation getChildById(@RequestBody Integer childID) {
        return userService.getChildByID(childID);
    }

    @Autowired
    ChildinformationtableMapper childinformationtableMapper;

    @GetMapping("/getChildById2")
    public Childinformationtable getChildById2(@RequestBody Integer childID) {
        System.out.println(childID);
        System.out.println("-------------");

        return childinformationtableMapper.selectById(childID);
    }

    @PostMapping("/saveDietaryRecords")
    public Boolean saveDietaryRecords(@RequestBody ChildDietaryRecords childDietaryRecords) {
        userService.saveDietaryRecords(childDietaryRecords);
        return true;
    }

    @PostMapping("/saveSportRecords")
    public Boolean saveSportRecords(@RequestBody ChildSportRecords childSportRecords) {
        userService.saveSportRecords(childSportRecords);
        return true;
    }

    @PostMapping("/getSportList")
    public List<ChildSportRecords> getSportByChildID(@RequestBody Integer childID){
        return userService.getSportListByChildID(childID);
    }

    @PostMapping("/getDietaryList")
    public List<ChildDietaryRecords> getDietaryByChildID(@RequestBody Integer childID){



        List<ChildDietaryRecords> dietaryListByChildID = userService.getDietaryListByChildID(childID);
        return dietaryListByChildID;
    }

    @PostMapping("/saveReport")
    public Boolean saveReport(@RequestBody Report report){
        return userService.saveReport(report,report.getChildInformation().getChildID());
    }

    @PostMapping("/getReport")
    public List<Report> getReport(@RequestBody Integer childID){
        return userService.getReport(childID);
    }


}